import React from 'react';
import { connect } from 'dva';
import {
    Button, Card, Col, Row, Icon, Popconfirm,
    Spin, Divider, Form, Input, Radio, Table,message,Tooltip
} from 'antd';
import styles from './index.less';
import router from 'umi/router';
import InputText from '@/components/Input/index';
import AddPointRule from './addPointRule';
import EditPointRule from './editPointRule';
const FormItem = Form.Item;
const RadioGroup = Radio.Group;

@Form.create()

class Integral extends React.Component {
    constructor() {
        super();
        this.state={
            loading: true,
            loading2: true,
            isFetching2: false,
            souceData: [], //表单数据
            storePointData: [], //商铺数据
            pagination: {
                showSizeChanger: true,
                showTotal: total => `共 ${total} 条记录`,
                pageSize: 10,
                total: 0,
              },
            pageIndex: 1,
        }
    }
    componentWillMount() {
      window.Isoption = false;
    }

    componentDidMount() {
      window.Isoption = true;
        this.props.form.validateFields();
        this.getPointListWithPage();
        this.findStorePoint();
      }

      //分页tabel数据
      getPointListWithPage =() => {
        const { dispatch } = this.props;
        const {pageIndex} = this.state;
        dispatch({
            type: 'gradeCard/GetPointListWithPage',
            payload: {
                PageIndex: pageIndex,
                PageSize: this.state.pagination['pageSize'],
            },
            callBack: {
                success: res => {
                    if(res.Code ===0) {
                        this.setState({
                            loading: false,
                            pagination: {
                                pageSize: this.state.pagination['pageSize'],
                                current: pageIndex,
                                total: res.Data.Total,
                                showSizeChanger: true,
                                showTotal: total => `共 ${total} 条记录`,
                              },
                            souceData: res.Data.DataList
                        })
                    }
                },
                error: res => {
                    message.error(res.Msg);
                },
            }
        })
      }

      //商铺积分信息
      findStorePoint =() => {
        const { dispatch } = this.props;
        dispatch({
            type: 'gradeCard/FindStorePoint',
            callBack: {
                success: res => {
                    if(res.Code ===0) {
                        this.setState({
                            loading2: false,
                            storePointData: res.Data
                        })
                        this.props.form.setFieldsValue({
                            name: res.Data.Name?res.Data.Name:'积分'
                        })
                    }
                },
                error: res => {
                    message.error(res.Msg);
                },
            }
        })
      }

      //刷新页面
      clickrefrech = () => {
        this.setState({
            loading: true
        }, () => {
            this.getPointListWithPage();
        })
      }

      //tab切换
      onTableChange =(pagination, filters, sorter) => {
        this.setState({
            loading: true,
            pagination: {
              pageSize: pagination.pageSize,
              total: pagination.total,
              showSizeChanger: true,
              showTotal: total => `共 ${total} 条记录`,
            },
            pageIndex: pagination.current,
        }, () => {
            this.getPointListWithPage();
        }
    )}

      handleSubmit=(e) => {
        e.preventDefault();
        let { dispatch } = this.props;
        this.setState({
            isFetching2: true
        })
        this.props.form.validateFields((err, values) => {
            if(!err) {
                dispatch({
                    type: 'gradeCard/SetStorePoint',
                    payload: {
                        Name: values.name,
                        ClearRuleType: values.rule
                    },
                    callBack: {
                        success: res => {
                            if(res.Code ===0) {
                                this.setState({
                                    isFetching2: false
                                })
                                message.success('保存成功');
                            } else {
                                message.error(res.Msg);
                                this.setState({
                                    isFetching2: false
                                })
                            }
                        },
                        error: res => {
                            message.error(res.Msg);
                            this.setState({
                                isFetching2: false
                            })
                        }
                    }
                })
            } else {
                this.setState({
                    isFetching2: false
                })
            }
        })
      }

     // 修改名称
    onTextChange = (v) => {
        this.setState({ name: v.target.value  });
        this.props.form.setFieldsValue({
          name: v.target.value
        })
      }

    // 校验名
    checkName = (e) => {
        this.props.form.validateFields(['name'], { force: true });
    }

    //删除
    clickDelete =(Id) => {
        let { dispatch } = this.props;
        dispatch({
            type: 'gradeCard/DeleteStorePoint',
            payload: {
                Id: Id
            },
            callBack: {
                success: res=> {
                    if(res.Code ===0) {
                        message.success('删除成功');
                        this.setState({
                            loading: true
                        })
                        this.getPointListWithPage();
                    }
                },
                error: res => {
                    message.error(res.Msg);
                }
            }
        })
    }


    render() {
        const {getFieldDecorator} = this.props.form;
        const {souceData, loading, storePointData, loading2} = this.state;
        const ruleTitle = (
            <span>
                1.每成功交易笔数：条件之间相互不重叠，每笔订单只执行一条规则，从低条件到高条件顺序循环；如：完成第一笔订单，则执行“每成功交易1笔”的规则；完成第二笔订单，则执行“每成功交易2笔”的规则；当最高条件规则也执行后，又从最低的条件开始向上执行 <br/>
                2.每购买xx金额，规则：取订单可满足的门槛最高的规则发放。
            </span>
        );
        const formItemLayout = {
            labelCol: {span: 3},
            wrapperCol: { span: 5 },
        };
        const formItemLayout2 = {
            labelCol: {span: 3},
            wrapperCol: { span: 16 },
        };

        const columns = [{
            title: '奖励条件',
            dataIndex: 'Name',
            key: 'Name',
          }, {
            title: '单笔奖励积分',
            dataIndex: 'Points',
            key: 'Points',
            align: 'right'
          }, {
            title: '创建时间',
            dataIndex: 'CreateTime',
            key: 'CreateTime',
          }, {
            title: '最近更新时间',
            dataIndex: 'ModifiedTime',
            key: 'ModifiedTime',
          }, {
            title: '已奖励总积分',
            key: 'AccumulatedPoints',
            dataIndex: 'AccumulatedPoints',
            align: 'right'
          }, {
            title: '操作',
            key: 'action',
            align: 'right',
            render: (text, record) => (
              <span>
                <a href="javascript:;"
                    onClick={() => {
                        const title = '编辑奖励规则';
                        const id = record.Id;
                        this.editPointRule.show({action: 'editPoint',id, title}, this.clickrefrech)
                    }}
                >
                    编辑
                </a>
                <Divider type="vertical" />
                <Popconfirm
                    placement="topRight"
                    title="确认删除?"
                    okText="确认"
                    cancelText="取消"
                    onConfirm={() => this.clickDelete(record.Id)}
                >
                    <a href="javascript:;">删除</a>
                </Popconfirm>
              </span>
            ),
          }];

        return (
            <Spin spinning={loading2}>
                <Card className={styles.headCard} bordered={false}>
                    <div className={styles.headItem}>
                        <div>
                            <div><span style={{marginRight:'4px'}}>可使用积分</span><Tooltip placement="rightTop" title="店铺所有用户拥有的积分总数" overlayStyle={{background: '#fff'}}>
                                <Icon type="question-circle" style={{color: 'grey'}}/>
                            </Tooltip></div>
                            <div>{storePointData.AccumulatedCanUsePoints}</div>
                        </div>
                    </div>
                    <Divider type="vertical" className={styles.divider}/>
                    <div className={styles.headItem}>
                        <div>
                            <div><span style={{marginRight:'4px'}}>累计发放积分</span><Tooltip placement="rightTop" title="店铺所有用户累计获得的积分总数" overlayStyle={{background: '#fff'}}>
                                <Icon type="question-circle" style={{color: 'grey'}}/>
                            </Tooltip></div>
                            <div>{storePointData.AccumulatedPoints}</div>
                        </div>
                    </div>
                    <Divider type="vertical" className={styles.divider}/>
                    <div className={styles.headItem} style={{borderRight:0}}>
                        <div>
                            <div><span style={{marginRight:'4px'}}>累计消耗积分</span><Tooltip placement="rightTop" title="店铺所有用户累计使用过的积分总数" overlayStyle={{background: '#fff'}}>
                                <Icon type="question-circle" style={{color: 'grey'}}/>
                            </Tooltip></div>
                            <div>{storePointData.AccumulatedUsedPoints}</div>
                        </div>
                    </div>
                </Card>
                <Card
                    title={
                        <span className={styles.titleSpan}>设置积分规则</span>
                    }
                    style={{marginTop: 16}}
                    bordered={false}
                >
                        <Form onSubmit={this.handleSubmit}>
                            <Form.Item
                                label="积分名称"
                                {...formItemLayout}
                            >
                                {
                                    getFieldDecorator('name', {
                                        initialValue: '积分',
                                        rules: [
                                            {required: true, message: '积分名称必填'},
                                        ],
                                        validateTrigger: 'onBlur'
                                    })(
                                        <InputText name="name" onChange={this.onTextChange} onBlur={this.checkName} showtotal maxLength={6} />
                                )
                                }
                            </Form.Item>
                            <Form.Item
                                label="积分清零规则"
                                {...formItemLayout2}
                            >
                                {
                                    getFieldDecorator('rule', {
                                        initialValue: storePointData.ClearRuleType,
                                        rules: []
                                    })(
                                        <RadioGroup onChange={this.onChange}>
                                            <Radio value={1}>不清零</Radio>
                                            <Radio value={2}>自然年清零所有积分</Radio>
                                        </RadioGroup>
                                    )
                                }
                            </Form.Item>
                            <Row>
                                <Col offset={3}>
                                    <Button
                                        type="primary"
                                        htmlType="submit"
                                        style={{marginBottom: 8}}
                                        loading={this.state.isFetching2}
                                    >
                                        保存
                                    </Button>
                                </Col>
                            </Row>
                        </Form>
                </Card>
                <Card
                    style={{marginTop: 16}}
                    title={
                        <span>
                            <span className={styles.titleSpan}>积分奖励设置</span>
                            <Tooltip placement="rightTop" title={ruleTitle} overlayStyle={{background: '#fff'}}>
                                <Icon type="question-circle" style={{color: 'grey'}}/>
                            </Tooltip>
                        </span>
                    }
                    bordered={false}
                >
                    <Spin spinning={loading}>
                      <Button
                          type="primary"
                          style={{marginBottom: 16, marginLeft: 16}}
                          onClick={()=> {
                              const title = '新增奖励规则';
                              this.addPointRule.show({action: 'addPoint', title}, this.clickrefrech)
                          }}
                      >
                          新增奖励规则
                      </Button>
                      <Table
                          columns={columns}
                          dataSource={souceData}
                          rowKey={record => record.Id}
                          onChange={this.onTableChange}
                          pagination={this.state.pagination}
                      />
                    </Spin>
                </Card>
                <AddPointRule
                    ref={e => {
                        this.addPointRule = e;
                    }}
                />
                <EditPointRule
                    ref={e => {
                        this.editPointRule = e;
                    }}
                />
            </Spin>
        )
    }
}

export default connect(({global }) => ({
    global,
}))(Integral);
